import requests
import json
import time
import logging
from prettyprinter import cpprint
 
class ZenTaoAPI(object):
    def __init__(self, account, password, host="http://127.0.0.1/zentao/"):
        self.url = host
        self.headers = {
            'Content-Type': "application/x-www-form-urlencoded"
        }
        self.data = {
            "account": account,
            "password": password
        }
 
        self.s = requests.session()
 
    def get_session(self):
        url = self.url + 'api-getSessionID.json'
        self.s.get(url)
 
    def login(self):
        url = self.url + "user-login.json"
        response = self.s.post(url, headers=self.headers, data=self.data)
 
        if "登录失败" in response.content.decode("utf-8"):
            return False
        else:
            return True
 
    def logout(self):
        url = self.url + "user-logout.json"
        response = self.s.post(url, headers=self.headers, data=self.data)
        return response.status_code

    def api(self, mod, func, *params, datas={}):
        url = self.url + "%s-%s-%s.json"%(mod, func, '-'.join(params))
        headers = {
            'Content-Type': "application/x-www-form-urlencoded; charset=utf-8"
        }
        response = self.s.post(url, headers=headers, data=datas)
        if response.status_code != 200:
            logging.warn('http error:' + response.status_code)
            return False
        ret = json.loads(response.json()['data'])
        return ret
 
if __name__ == "__main__":
    try:
        from config import *
    except:
        user='admin'
        password='123456'
    z = ZenTaoAPI(user, password)
    z.get_session()
    z.login()
    ret = z.api('story', 'view', str(1))
    cpprint(ret)
    z.logout()
